package com.xhh.nphm.gaoxin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhh.nphm.common.annotation.RepeatSubmit;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.DateUtils;
import com.xhh.nphm.common.utils.ShiroUtils;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.bean.BeanUtils;
import com.xhh.nphm.gaoxin.entity.GxqTwfSendBackEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormBaseEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormLogEty;
import com.xhh.nphm.gaoxin.service.GxqITelWFLogService;
import com.xhh.nphm.gaoxin.service.GxqIWfSendBackService;
import com.xhh.nphm.gaoxin.service.GxqIWorkFormBaseService;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.service.IDeptService;
import com.xhh.nphm.system.service.impl.CommonServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/gaoxin/system/sendBack")
public class GxqWfSendBackController extends BaseController {
    String prefix = "system/gaoxin/sendBack";
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private CommonServiceImpl commonService;
    @Autowired
    private GxqSendSonCtrl GxqSendSonCtrl;
    @Autowired
    private GxqITelWFLogService gxqTelWFLogService;
    @Autowired
    private GxqIWfSendBackService gxqWfSendBackService;
    @Autowired
    private GxqIWorkFormBaseService gxqworkFormBaseService;



    /**
     * 拟办部门页面
     *
     * @param
     * @param
     * @return
     */
    @GetMapping("/proposed/{pkId}")
    public ModelAndView proposed(@PathVariable("pkId") Integer pkId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        Long deptId = user.getDeptId();
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqworkFormBaseService.getById(pkId);
        GxqTwfSendBackEty sendBackEty = GxqTworkFormBaseEty.getTwfSendBackEty();
        sendBackEty.setSdeptId(deptId.toString());
        sendBackEty.setSdeptName(user.getDeptName());
        sendBackEty.setSuserNo(user.getUserNo());
        sendBackEty.setSuserName(user.getUserName());
        map.put("workFormBase", GxqTworkFormBaseEty);
        map.put("wfId", GxqTworkFormBaseEty.getPkId());
        map.put("sdeptName", user.getDept().getDeptShort());
        map.put("sdeptId", sendBackEty.getSdeptId());
        map.put("suserName", sendBackEty.getSuserName());
        map.put("suserNo", sendBackEty.getSuserNo());
        map.put("deptId", user.getDeptId());
        map.put("sendTime",DateUtils.getTime());
        return new ModelAndView("system/gaoxin/test/deptdiag");
    }

    /**
     * 进入修改拟派工单的页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/editDept/{wfId}/{pkId}")
    public ModelAndView editDept(@PathVariable("wfId") Integer wfId, @PathVariable("pkId") Integer pkId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        Long deptId = user.getDeptId();
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqworkFormBaseService.getById(wfId);
        GxqTwfSendBackEty sendBackEty = gxqWfSendBackService.getById(pkId);
        GxqTworkFormBaseEty.setTwfSendBackEty(sendBackEty);
        sendBackEty.setSdeptId(deptId.toString());
        sendBackEty.setSdeptName(user.getDeptName());
        sendBackEty.setSuserNo(user.getUserNo());
        sendBackEty.setSuserName(user.getUserName());
        map.put("workFormBase", GxqTworkFormBaseEty);
        map.put("wfId", GxqTworkFormBaseEty.getPkId());
        map.put("sdeptName", sendBackEty.getSdeptName());
        map.put("sdeptId", sendBackEty.getSdeptId());
        map.put("suserName", sendBackEty.getSuserName());
        map.put("suserNo", sendBackEty.getSuserNo());

        return new ModelAndView("system/gaoxin/test/editDeptDiag");
    }

    /**
     * 修改拟派工单信息
     * @param GxqTworkFormBaseEty 带有拟派工单的电话工单
     * @return 响应结果
     */
    @PostMapping("/editDept")
    public AjaxResult editDept(GxqTworkFormBaseEty GxqTworkFormBaseEty) {
        //保存响应结果
        boolean flag = false;
        GxqTwfSendBackEty GxqTwfSendBackEty = GxqTworkFormBaseEty.getTwfSendBackEty();
//        if (GxqTwfSendBackEty.getWfId() > 0) {
            UpdateWrapper<GxqTwfSendBackEty> sbWrapper = new UpdateWrapper<>();
            sbWrapper
                    .set("SeqCode", GxqTwfSendBackEty.getSeqCode())
                    .set("SeqName", GxqTwfSendBackEty.getSeqName())
                    .set("SbdeptId", GxqTwfSendBackEty.getSbdeptId())
                    .set("SbdeptName", GxqTwfSendBackEty.getSbdeptName())
                    .set("SortCode", GxqTwfSendBackEty.getSortCode())
                    .set("SortName", GxqTwfSendBackEty.getSortName())
                    .set("DealCode", GxqTwfSendBackEty.getDealCode())
                    .set("DealName", GxqTwfSendBackEty.getDealName())
                    .set("SendDesc", GxqTwfSendBackEty.getSendDesc())
                    .set("BackLimit", GxqTwfSendBackEty.getBackLimit())
                    .set("SendRemark", GxqTwfSendBackEty.getSendRemark())
                    .eq("PkId", GxqTwfSendBackEty.getPkId());
            //执行修改方法
            flag = gxqWfSendBackService.update(sbWrapper);
            //判断是否修改成功
            if (flag) {
                // 记录电话派单操作日志
                SysUser user = ShiroUtils.getSysUser();
                GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
                //[tWorkFormBase]PkId
                etyLog.setWfId(GxqTwfSendBackEty.getWfId());
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                String temp = "调整办理部门及要求(" + GxqTwfSendBackEty.getSbdeptName() + ")";
                etyLog.setOpAction("修改");
                etyLog.setOpBtnId(-1);
                etyLog.setWsDesc(temp);
                etyLog.setWsOpen(1);
                etyLog.setOpDesc(temp);
                etyLog.setEffectFlag(-1);
                gxqTelWFLogService.save(etyLog);
            }
//        }
        return toAjax(flag);
    }

    /**
     * 2023/1/10
     * 修改GxqTwfSendBackEty工单信息
     * @param GxqTwfSendBackEty
     * @return 响应结果
     */
    @PostMapping("/editDeptJson")
    public AjaxResult editDeptJson(GxqTwfSendBackEty GxqTwfSendBackEty) {
        //保存响应结果
        boolean flag = false;
        // if (GxqTwfSendBackEty.getWfId() > 0) {
            UpdateWrapper<GxqTwfSendBackEty> sbWrapper = new UpdateWrapper<>();
            sbWrapper
                    .set("SeqCode", GxqTwfSendBackEty.getSeqCode())
                    .set("SeqName", GxqTwfSendBackEty.getSeqName())
                    .set("SbdeptId", GxqTwfSendBackEty.getSbdeptId())
                    .set("SbdeptName", GxqTwfSendBackEty.getSbdeptName())
                    .set("SortCode", GxqTwfSendBackEty.getSortCode())
                    .set("SortName", GxqTwfSendBackEty.getSortName())
                    .set("DealCode", GxqTwfSendBackEty.getDealCode())
                    .set("DealName", GxqTwfSendBackEty.getDealName())
                    .set("SendDesc", GxqTwfSendBackEty.getSendDesc())
                    .set("BackLimit", GxqTwfSendBackEty.getBackLimit())
                    .set("SendRemark", GxqTwfSendBackEty.getSendRemark())
                    .set("isDelay", GxqTwfSendBackEty.getIsDelay())
                    .eq("PkId", GxqTwfSendBackEty.getPkId());
            //执行修改方法
            flag = gxqWfSendBackService.update(sbWrapper);
            //判断是否修改成功
            if (flag) {
                // 记录电话派单操作日志
                SysUser user = ShiroUtils.getSysUser();
                GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
                //[tWorkFormBase]PkId
                etyLog.setWfId(GxqTwfSendBackEty.getWfId());
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                String temp = "调整办理部门及要求(" + GxqTwfSendBackEty.getSbdeptName() + ")";
                etyLog.setOpAction("修改");
                etyLog.setOpBtnId(-1);
                etyLog.setWsDesc(temp);
                etyLog.setWsOpen(1);
                etyLog.setOpDesc(temp);
                etyLog.setEffectFlag(-1);
                gxqTelWFLogService.save(etyLog);
            }
       // }
        return toAjax(flag);
    }

    /**
     * 拟派工单
     * resendType 1重新派单
     * 创建工单后的派单
     * 重新派单
     * @param
     * @return
     */
    @RequestMapping("simulacrum")
    @RepeatSubmit
    public AjaxResult simulacrum(GxqTwfSendBackEty GxqTwfSendBackEty, Integer resendType, String zpFlag) {
        if (IS_GAOXIN()){
            return simulacrum_gxq(GxqTwfSendBackEty,resendType,zpFlag);
        }else{
            return simulacrum_general(GxqTwfSendBackEty,resendType);
        }
    }



    public AjaxResult simulacrum_general(GxqTwfSendBackEty GxqTwfSendBackEty, Integer resendType) {
        String deptId = getSysUser().getDeptId().toString();
        if (GxqTwfSendBackEty.getFpDirect() == 1) {
            //xnb直派
            simulacrumXnb(GxqTwfSendBackEty,deptId);
        }
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqworkFormBaseService.getById(GxqTwfSendBackEty.getWfId());
        GxqTwfSendBackEty etyMain = new GxqTwfSendBackEty();
        if (GxqTworkFormBaseEty != null) {
            // TODO: 未完善
            // 拟派给主办单位  统一为主办单位     协办单位不需要了
            etyMain.setGetDealPk(GxqTworkFormBaseEty.getGetDealPk());
            etyMain.setCallId(GxqTworkFormBaseEty.getCallId());
            etyMain.setTapeId(GxqTworkFormBaseEty.getTapeId());
            etyMain.setWfId(GxqTworkFormBaseEty.getPkId());
        }
        int oriLevel = 1;
        if (!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        etyMain.setOriLevel(oriLevel);
        etyMain.setSeqCode(GxqTwfSendBackEty.getSeqCode());
        etyMain.setSeqName(GxqTwfSendBackEty.getSeqName());
        etyMain.setSendState(10);
        etyMain.setSendDesc(GxqTwfSendBackEty.getSendDesc());
        etyMain.setSdeptId(GxqTwfSendBackEty.getSdeptId());
        etyMain.setSdeptName(GxqTwfSendBackEty.getSdeptName());
        etyMain.setSuserNo(GxqTwfSendBackEty.getSuserNo());
        etyMain.setSuserName(GxqTwfSendBackEty.getSuserName());
        etyMain.setSendTime(new Date());
        etyMain.setSendRemark(GxqTwfSendBackEty.getSendRemark());
        etyMain.setSattachPath(GxqTwfSendBackEty.getSattachPath());
        etyMain.setSattachName(GxqTwfSendBackEty.getSattachName());
        etyMain.setSendSpare(GxqTwfSendBackEty.getSendSpare());
        etyMain.setBackState(0);
        etyMain.setSortCode("11");
        etyMain.setSortName("主办");
        etyMain.setDealCode("11");
        etyMain.setDealName(GxqTwfSendBackEty.getDealName());
        etyMain.setBackLimit(GxqTwfSendBackEty.getBackLimit());
        etyMain.setIsGoBack(GxqTwfSendBackEty.getIsGoBack());
        //TODO：promisesTime不清楚怎么来的
        etyMain.setPromisesTime(GxqTwfSendBackEty.getBackLimit());
//        bDeptId = arrDetpIdX[i];
//        bDeptName = arrDetpNameX[i];
        if (GxqTwfSendBackEty.getSbdeptId() == null) {
            etyMain.setSbdeptId("-1");
        }
        if (GxqTwfSendBackEty.getSbdeptName() == null) {
            etyMain.setSbdeptName("单位名称");
        }
        etyMain.setSbdeptId(GxqTwfSendBackEty.getSbdeptId());
        etyMain.setSbdeptName(GxqTwfSendBackEty.getSbdeptName());
        //重新派单，页面上拿不到父派单id
        Integer pid = GxqTwfSendBackEty.getPid();
        if(!"304".equals(deptId) && (pid == null || pid <= 0)) {
            //不用每个地方都从页面把pid传够了，容易绕晕，但父id不是百分百准确
            QueryWrapper<GxqTwfSendBackEty> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("top 1 pkId");
            queryWrapper.eq("wfId", GxqTwfSendBackEty.getWfId());
            queryWrapper.eq("SBDeptId",deptId);
            queryWrapper.orderByDesc("pkId");
            List<GxqTwfSendBackEty> list = gxqWfSendBackService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                pid = list.get(0).getPkId();
            }
        }
        etyMain.setPid(pid);
        int row = 0;
        boolean flag = false;
        //拟派多个部门
        if(GxqTwfSendBackEty.getSbdeptId().indexOf(',') != -1){
            String[] ids = GxqTwfSendBackEty.getSbdeptId().split(",");
            String[] names = GxqTwfSendBackEty.getSbdeptName().split(",");
            String sendDesc = GxqTwfSendBackEty.getSendDesc();
            for (int i = 0; i < ids.length; i++) {
                etyMain.setSendDesc(sendDesc.replace(GxqTwfSendBackEty.getSbdeptName(),names[i]));
                etyMain.setSbdeptId(ids[i]);
                etyMain.setSbdeptName(names[i]);
                flag = gxqWfSendBackService.save(etyMain);
                if (flag) {
                    row = 1;
                    // 记录电话派单操作日志
                    SysUser user = ShiroUtils.getSysUser();
                    //todo 日志
                    GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
                    etyLog.setWfId(GxqTwfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                    etyLog.setOpDeptNo(user.getDeptId().toString());
                    etyLog.setOpDeptName(user.getDeptName());
                    etyLog.setOpUserNo(user.getUserNo());
                    etyLog.setOpUserName(user.getUserName());
                    etyLog.setOpAction("提交初稿");
                    etyLog.setOpBtnId(-1);
                    String temp = "";
                    String desc = "";
                    temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                    desc = "主办：";
                    desc += temp;
                    etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                    etyLog.setWsOpen(1); //website ShowFlag
                    etyLog.setOpDesc("提交内容概要：" + desc);
                    etyLog.setEffectFlag(1);
                    gxqTelWFLogService.save(etyLog);
                }
            }
        }
        //拟派一个部门
        else {
            flag = gxqWfSendBackService.save(etyMain);
            if (flag) {
                row = 1;
                // 记录电话派单操作日志
                SysUser user = ShiroUtils.getSysUser();
                //todo 日志
                GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
                etyLog.setWfId(GxqTwfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                etyLog.setOpAction("提交初稿");
                etyLog.setOpBtnId(-1);
                String temp = "";
                String desc = "";
                temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                desc = "主办：";
                desc += temp;
                etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                etyLog.setWsOpen(1); //website ShowFlag
                etyLog.setOpDesc("提交内容概要：" + desc);
                etyLog.setEffectFlag(1);
                gxqTelWFLogService.save(etyLog);
            }
        }

        //更新父级派单状态 etyMain新增下派单子的id
        commonDao.proTsubBackState(GxqTwfSendBackEty.getWfId(),etyMain.getPkId());
//        if(!"304".equals(deptId)) {
//            commonDao.proTsubBackState(GxqTwfSendBackEty.getWfId(),etyMain.getPkId());
//        }
        return toAjax(row);
    }

    public AjaxResult simulacrum_gxq(GxqTwfSendBackEty GxqTwfSendBackEty, Integer resendType, String zpFlag) {
        SysUser user = ShiroUtils.getSysUser();
        String deptId = user.getDeptId().toString();
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqworkFormBaseService.getById(GxqTwfSendBackEty.getWfId());
        GxqTwfSendBackEty etyMain = new GxqTwfSendBackEty();
        if (GxqTworkFormBaseEty != null) {
            // TODO: 未完善
            // 拟派给主办单位  统一为主办单位     协办单位不需要了
            etyMain.setGetDealPk(GxqTworkFormBaseEty.getGetDealPk());
            etyMain.setCallId(GxqTworkFormBaseEty.getCallId());
            etyMain.setTapeId(GxqTworkFormBaseEty.getTapeId());
            etyMain.setWfId(GxqTworkFormBaseEty.getPkId());
        }
        int oriLevel = 1;
        if (!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        etyMain.setOriLevel(oriLevel);
        etyMain.setSeqCode(GxqTwfSendBackEty.getSeqCode());
        etyMain.setSeqName(GxqTwfSendBackEty.getSeqName());
        etyMain.setSendState(10);
        etyMain.setSendDesc(GxqTwfSendBackEty.getSendDesc());
        etyMain.setSdeptId(GxqTwfSendBackEty.getSdeptId());
        etyMain.setSdeptName(GxqTwfSendBackEty.getSdeptName());
        etyMain.setSuserNo(GxqTwfSendBackEty.getSuserNo());
        etyMain.setSuserName(GxqTwfSendBackEty.getSuserName());
        etyMain.setSendTime(new Date());
        etyMain.setSendRemark(GxqTwfSendBackEty.getSendRemark());
        etyMain.setSattachPath(GxqTwfSendBackEty.getSattachPath());
        etyMain.setSattachName(GxqTwfSendBackEty.getSattachName());
        etyMain.setSendSpare(GxqTwfSendBackEty.getSendSpare());
        etyMain.setBackState(0);
        etyMain.setSortCode("11");
        etyMain.setSortName("主办");
        etyMain.setDealCode("11");
        etyMain.setDealName(GxqTwfSendBackEty.getDealName());
        etyMain.setBackLimit(GxqTwfSendBackEty.getBackLimit());
        etyMain.setIsGoBack(GxqTwfSendBackEty.getIsGoBack());
        //TODO：promisesTime不清楚怎么来的
        etyMain.setPromisesTime(GxqTwfSendBackEty.getBackLimit());
        if (GxqTwfSendBackEty.getSbdeptId() == null) {
            etyMain.setSbdeptId("-1");
        }
        if (GxqTwfSendBackEty.getSbdeptName() == null) {
            etyMain.setSbdeptName("单位名称");
        }
        etyMain.setSbdeptId(GxqTwfSendBackEty.getSbdeptId());
        etyMain.setSbdeptName(GxqTwfSendBackEty.getSbdeptName());
        //重新派单，页面上拿不到父派单id
        Integer pid = GxqTwfSendBackEty.getPid();
        if(!"304".equals(deptId) && (pid == null || pid <= 0)) {
            //不用每个地方都从页面把pid传够了，容易绕晕，但父id不是百分百准确
            QueryWrapper<GxqTwfSendBackEty> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("top 1 pkId");
            queryWrapper.eq("wfId", GxqTwfSendBackEty.getWfId());
            queryWrapper.eq("SBDeptId", deptId);
            queryWrapper.orderByDesc("pkId");
            List<GxqTwfSendBackEty> list = gxqWfSendBackService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                pid = list.get(0).getPkId();
            }
        }
        etyMain.setPid(pid);
        int row = 0;
        boolean flag = false;
        //拟派多个部门
        if(GxqTwfSendBackEty.getSbdeptId().indexOf(',') != -1){
            String[] ids = GxqTwfSendBackEty.getSbdeptId().split(",");
            String[] names = GxqTwfSendBackEty.getSbdeptName().split(",");
            String[] zpFlags = zpFlag.split(",");
            String sendDesc = GxqTwfSendBackEty.getSendDesc();
            for (int i = 0; i < ids.length; i++) {
                etyMain.setSendDesc(sendDesc.replace(GxqTwfSendBackEty.getSbdeptName(),names[i]));
                etyMain.setSbdeptId(ids[i]);
                etyMain.setSbdeptName(names[i]);
                etyMain.setSdeptId(GxqTwfSendBackEty.getSdeptId());
                etyMain.setSdeptName(GxqTwfSendBackEty.getSdeptName());
                etyMain.setPid(pid);
                if (zpFlags[i].equals("10")){
                    etyMain.setSendSpare("1"); //直派
                    GxqSendSonCtrl.directWF(etyMain,user);
                }else {
                    flag = gxqWfSendBackService.save(etyMain);
                    if (flag) {
                        row = 1;
                        // 记录电话派单操作日志
                        //todo 日志
                        GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
                        etyLog.setWfId(GxqTwfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                        etyLog.setOpDeptNo(deptId);
                        etyLog.setOpDeptName(user.getDeptName());
                        etyLog.setOpUserNo(user.getUserNo());
                        etyLog.setOpUserName(user.getUserName());
                        etyLog.setOpAction("提交初稿");
                        etyLog.setOpBtnId(-1);
                        String temp = "";
                        String desc = "";
                        temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                        desc = "主办：";
                        desc += temp;
                        etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                        etyLog.setWsOpen(1); //website ShowFlag
                        etyLog.setOpDesc("提交内容概要：" + desc);
                        etyLog.setEffectFlag(1);
                        gxqTelWFLogService.save(etyLog);
                    }
                }
                //更新父级派单状态 etyMain新增下派单子的id
                commonDao.proTsubBackState(GxqTwfSendBackEty.getWfId(),etyMain.getPkId());
            }
        }
        //拟派一个部门
        else {
            if (zpFlag != null && zpFlag.equals("0")) {//派给一个部门
                flag = gxqWfSendBackService.save(etyMain);
                if (flag) {
                    row = 1;
                    // 记录电话派单操作日志
                    //todo 日志
                    GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
                    etyLog.setWfId(GxqTwfSendBackEty.getWfId()); //[tWorkFormBase]PkId
                    etyLog.setOpDeptNo(deptId);
                    etyLog.setOpDeptName(user.getDeptName());
                    etyLog.setOpUserNo(user.getUserNo());
                    etyLog.setOpUserName(user.getUserName());
                    etyLog.setOpAction("提交初稿");
                    etyLog.setOpBtnId(-1);
                    String temp = "";
                    String desc = "";
                    temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
                    desc = "主办：";
                    desc += temp;
                    etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                    etyLog.setWsOpen(1); //website ShowFlag
                    etyLog.setOpDesc("提交内容概要：" + desc);
                    etyLog.setEffectFlag(1);
                    gxqTelWFLogService.save(etyLog);
                }
            }else {
                //xnb直派
                etyMain.setSendSpare("1"); //直派
                GxqSendSonCtrl.directWF(etyMain,user);
            }
            //更新父级派单状态 etyMain新增下派单子的id
            commonDao.proTsubBackState(GxqTwfSendBackEty.getWfId(),etyMain.getPkId());
        }
        return toAjax(row);
    }


    /**
     * Xnb直派工单
     */
    private void simulacrumXnb(GxqTwfSendBackEty GxqTwfSendBackEty,String deptId){
        SysUser user = ShiroUtils.getSysUser();
        //区县政府
        GxqTwfSendBackEty sbQX = new GxqTwfSendBackEty();
        //xnb直派 给区县初始化一条记录
        sbQX.setGetDealPk(GxqTwfSendBackEty.getGetDealPk());
        sbQX.setCallId(GxqTwfSendBackEty.getCallId());
        sbQX.setTapeId(GxqTwfSendBackEty.getTapeId());
        sbQX.setWfId(GxqTwfSendBackEty.getWfId());
        int oriLevel = 1;
        if(!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        sbQX.setOriLevel(oriLevel);
        sbQX.setSeqCode(GxqTwfSendBackEty.getSeqCode());
        sbQX.setSeqName(GxqTwfSendBackEty.getSeqName());
        //已派下级
        sbQX.setSendState(23);
        sbQX.setSortCode(GxqTwfSendBackEty.getSortCode());
        sbQX.setSortName(GxqTwfSendBackEty.getSortName());
        sbQX.setDealCode(GxqTwfSendBackEty.getDealCode());
        sbQX.setDealName(GxqTwfSendBackEty.getDealName());
        sbQX.setSbdeptId(GxqTwfSendBackEty.getSbdeptId());
        sbQX.setSbdeptName(GxqTwfSendBackEty.getSbdeptName());
        sbQX.setSendDesc(GxqTwfSendBackEty.getSendDesc());
        sbQX.setSendTime(GxqTwfSendBackEty.getSendTime());
        sbQX.setBackLimit(GxqTwfSendBackEty.getBackLimit());
        sbQX.setSendRemark(GxqTwfSendBackEty.getSendRemark());
        sbQX.setSendSpare("1");
        sbQX.setSattachPath(GxqTwfSendBackEty.getSattachPath());
        sbQX.setSdeptId(user.getDeptId().toString());
        sbQX.setSdeptName(user.getDeptName());
        //拟派多个部门
        if(GxqTwfSendBackEty.getSbdeptId().indexOf(',') != -1){
            String[] ids = GxqTwfSendBackEty.getSbdeptId().split(",");
            String[] names = GxqTwfSendBackEty.getSbdeptName().split(",");
            String sendDesc = GxqTwfSendBackEty.getSendDesc();
            for (int i = 0; i < ids.length; i++) {
                sbQX.setSbdeptId(ids[i]);
                sbQX.setSbdeptName(names[i]);
                sbQX.setSendDesc(sendDesc.replace(GxqTwfSendBackEty.getSbdeptName(),names[i]));
                gxqWfSendBackService.save(sbQX);
            }
        }
        //拟派一个部门
        else {
            gxqWfSendBackService.save(sbQX);
        }
    }

    /**
     * 智能派单
     *
     * @param
     * @return
     */
    @RequestMapping("Intelligent")
    @RepeatSubmit
    public AjaxResult Intelligent(GxqTworkFormBaseEty workFormBaseEty) throws ParseException {
        SysUser user = ShiroUtils.getSysUser();
        String deptId = user.getDeptId().toString();
        GxqTworkFormBaseEty formBaseEty = gxqworkFormBaseService.getById(workFormBaseEty.getPkId());

        GxqTwfSendBackEty GxqTwfSendBackEty = formBaseEty.getTwfSendBackEty();
        GxqTwfSendBackEty.setSbdeptName(workFormBaseEty.getMark());
        String deptNo=commonService.selectDeptShort(GxqTwfSendBackEty.getSbdeptName());
        GxqTwfSendBackEty.setSbdeptId(deptNo);
        GxqTwfSendBackEty.setSdeptId(deptId);
        GxqTwfSendBackEty.setSdeptName(user.getDeptName());
        GxqTwfSendBackEty.setSuserNo(user.getUserNo());
        GxqTwfSendBackEty.setSuserName(user.getUserName());
        GxqTwfSendBackEty.setWfId(formBaseEty.getPkId());
        GxqTwfSendBackEty.setGetDealPk(formBaseEty.getGetDealPk());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        GxqTwfSendBackEty.setBackLimit(sdf.parse(commonService.getNxetBackLimit(5)));
        GxqTwfSendBackEty.setSeqName("初次交办");
        GxqTwfSendBackEty.setSeqCode("10");
        GxqTwfSendBackEty.setSortCode("11");
        GxqTwfSendBackEty.setSortName("主办");
        GxqTwfSendBackEty.setDealCode("11");
        GxqTwfSendBackEty.setDealName("研究办理");
        GxqTwfSendBackEty.setFpDirect(0);
        GxqTwfSendBackEty.setSendDesc("请 "+GxqTwfSendBackEty.getSbdeptName()+" 调查处理后直接与来话人联系，并将处理结果抄复我办。请注意来话人个人信息保密。");

        GxqTwfSendBackEty sbDir = new GxqTwfSendBackEty();
        sbDir = GxqTwfSendBackEty;
        sbDir.setSendState(10);  //未签收
        sbDir.setSendSpare("1");
        GxqTwfSendBackEty sbQX = new GxqTwfSendBackEty(); //区县政府

        try {
            if (GxqTwfSendBackEty.getFpDirect() > 0) {//xnb直派
                gxqWfSendBackService.save(sbQX);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqworkFormBaseService.getById(GxqTwfSendBackEty.getWfId());
        GxqTwfSendBackEty etyMain = new GxqTwfSendBackEty();
        if (GxqTworkFormBaseEty != null) {
            // TODO: 未完善
            // 拟派给主办单位  统一为主办单位     协办单位不需要了
            etyMain.setGetDealPk(GxqTworkFormBaseEty.getGetDealPk());
            etyMain.setCallId(GxqTworkFormBaseEty.getCallId());
            etyMain.setTapeId(GxqTworkFormBaseEty.getTapeId());
            etyMain.setWfId(GxqTworkFormBaseEty.getPkId());
        }
        int oriLevel = 1;
        if(!"304".equals(deptId) && deptId.length() == 3)
            oriLevel = 2;
        else
            oriLevel = deptId.length() / 3;
        etyMain.setOriLevel(oriLevel);
        etyMain.setSeqCode(GxqTwfSendBackEty.getSeqCode());
        etyMain.setSeqName(GxqTwfSendBackEty.getSeqName());
        etyMain.setSendState(10);
        etyMain.setSendDesc(GxqTwfSendBackEty.getSendDesc());
        etyMain.setSdeptId(GxqTwfSendBackEty.getSdeptId());
        etyMain.setSdeptName(GxqTwfSendBackEty.getSdeptName());
        etyMain.setSuserNo(GxqTwfSendBackEty.getSuserNo());
        etyMain.setSuserName(GxqTwfSendBackEty.getSuserName());
        etyMain.setSendTime(new Date());
        etyMain.setSendRemark(GxqTwfSendBackEty.getSendRemark());
        etyMain.setSattachPath(GxqTwfSendBackEty.getSattachPath());
        etyMain.setSattachName(GxqTwfSendBackEty.getSattachName());
        etyMain.setSendSpare(GxqTwfSendBackEty.getSendSpare());
        etyMain.setBackState(0);
        etyMain.setSortCode("11");
        etyMain.setSortName("主办");
        etyMain.setDealCode("11");
        etyMain.setDealName(GxqTwfSendBackEty.getDealName());
        etyMain.setBackLimit(GxqTwfSendBackEty.getBackLimit());
//        bDeptId = arrDetpIdX[i];
//        bDeptName = arrDetpNameX[i];
        if (GxqTwfSendBackEty.getSbdeptId() == null) {
            etyMain.setSbdeptId("-1");
        }
        if (GxqTwfSendBackEty.getSbdeptName() == null) {
            etyMain.setSbdeptName("单位名称");
        }
        etyMain.setSbdeptId(GxqTwfSendBackEty.getSbdeptId());
        etyMain.setSbdeptName(GxqTwfSendBackEty.getSbdeptName());
        int row = 0;
        boolean flag = gxqWfSendBackService.save(etyMain);
        if (flag) {
            row = 1;
            // 记录电话派单操作日志
            //todo 日志
            GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
            etyLog.setWfId(GxqTwfSendBackEty.getWfId()); //[tWorkFormBase]PkId
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setOpAction("提交初稿");
            etyLog.setOpBtnId(-1);
            String temp = "";
            String desc = "";
            temp = etyMain.getSbdeptName() != null ? etyMain.getSbdeptName() : "";
            if (temp.lastIndexOf(",") > 0)
                temp = temp.substring(0, temp.length() - 1);
            desc = "主办：";
            desc += temp;
            etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
            etyLog.setWsOpen(1); //website ShowFlag
            etyLog.setOpDesc("提交内容概要：" + desc);
            etyLog.setEffectFlag(1);
            gxqTelWFLogService.save(etyLog);
        }
        return toAjax(row);
    }

    /**
     * 拟派工单 列表显示
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("simulacrumList/{wfId}")
    public TableDataInfo simulacrumList(@PathVariable("wfId") Integer wfId) {
        startPage();
        List<GxqTwfSendBackEty> list = gxqWfSendBackService.selectByWfId(wfId);
        return getDataTable(list);
    }

    /**
     * 查询派发部门列表
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("distributeDept")
    public TableDataInfo distributeDept() {
        List<Map<String, String>> list = deptService.selectDistribute();
        return getDataTable(list);
    }

    /**
     * 查询派发部门 下级列表
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("sltDept")
    public TableDataInfo sltDept() {
        List<Map<String, String>> list = deptService.selectSltDept();
        return getDataTable(list);
    }


    /**
     * 审核工单
     *
     * @param GxqTwfSendBackEty
     * @return
     */
    @PostMapping("examine")
    @RepeatSubmit
    public AjaxResult examine(GxqTwfSendBackEty GxqTwfSendBackEty) {
        SysUser user = ShiroUtils.getSysUser();
        GxqTworkFormLogEty GxqTworkFormLogEty = GxqTwfSendBackEty.getTworkFormLogEty();
        GxqTworkFormLogEty.setOpUserNo(user.getUserNo());
        GxqTworkFormLogEty.setOpUserName(user.getUserName());
        GxqTworkFormLogEty.setOpDeptNo(user.getDeptId().toString());
        GxqTworkFormLogEty.setOpDeptName(user.getDeptName());
        GxqTworkFormLogEty.setOpBtnId(-1);
        GxqTwfSendBackEty.setSdeptName(user.getDeptName());
        GxqTwfSendBackEty.setSdeptId(user.getDeptId().toString());
        GxqTwfSendBackEty.setSuserNo(user.getUserNo());
        GxqTwfSendBackEty.setSuserName(user.getUserName());
        String temp = "";
        if (GxqTwfSendBackEty.getBackState() == 22) {
            temp = "不通过";
            GxqTwfSendBackEty.setBackRemark("不同意");
        }
        else {
            temp = "通过";
            GxqTwfSendBackEty.setBackRemark("同意");
        }
        temp = "审查" + GxqTwfSendBackEty.getSbdeptName() + "办理结果（" + temp + "）";
        GxqTworkFormLogEty.setOpDesc(temp);
        gxqTelWFLogService.save(GxqTworkFormLogEty);
        return toAjax(gxqWfSendBackService.updateSendBack(GxqTwfSendBackEty));
    }

    /**
     * 根据id 进行多选删除 和单个删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String... ids) {
        return toAjax(gxqWfSendBackService.deleteByIds(ids));
    }

    /**
     * 进入回访页面
     * @return
     */
    @GetMapping("sendBackRecord/{wfId}")
    public ModelAndView sendBackRecord(@PathVariable("wfId") Integer wfId,ModelMap map) {
        map.addAttribute("wfId",wfId);
        return new ModelAndView(prefix + "/sendBackRecord");
    }

    /**
     * 进入回访记录详情页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/sendBackRecordDetail/{wfId}/{pkId}")
    public ModelAndView sendBackRecordDetail(@PathVariable("wfId") Integer wfId, @PathVariable("pkId") Integer pkId, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        Long deptId = user.getDeptId();
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqworkFormBaseService.getById(wfId);
        GxqTwfSendBackEty sendBackEty = gxqWfSendBackService.getById(pkId);
        GxqTworkFormBaseEty.setTwfSendBackEty(sendBackEty);
        sendBackEty.setSdeptId(deptId.toString());
        sendBackEty.setSdeptName(user.getDeptName());
        sendBackEty.setSuserNo(user.getUserNo());
        sendBackEty.setSuserName(user.getUserName());
        map.put("workFormBase", GxqTworkFormBaseEty);
        map.put("wfId", GxqTworkFormBaseEty.getPkId());
        map.put("sdeptName", sendBackEty.getSdeptName());
        map.put("sdeptId", sendBackEty.getSdeptId());
        map.put("suserName", sendBackEty.getSuserName());
        map.put("suserNo", sendBackEty.getSuserNo());

        return new ModelAndView(prefix+"/sendBackRecordDetail");
    }

    /**
     * 派发下级部门
     * @param sender 拟派工单信息
     */
    @PostMapping("/sendSon")
    public void sendSon(GxqTwfSendBackEty sender){
        String desc = "";
        //当前用户登录信息
        SysUser user = getSysUser();
        //更新工单当前信息
        UpdateWrapper<GxqTworkFormBaseEty> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PkId", sender.getWfId());
        updateWrapper.set("WsUFlag", 1);
        updateWrapper.set("CrtStepId", 400);
        updateWrapper.set("CrtStepName", "市级部门处理中");
        updateWrapper.set("CrtStepTime", DateUtils.getNowDate());
        gxqworkFormBaseService.update(null, updateWrapper);
        //更新当前派单情况
        UpdateWrapper<GxqTwfSendBackEty> wrapper = new UpdateWrapper<>();
        wrapper.eq("PkId", sender.getPkId());
        wrapper.set("SendState", 23);
        gxqWfSendBackService.update(null, wrapper);

        GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
        //[tWorkFormBase]PkId
        etyLog.setWfId(sender.getWfId());
        etyLog.setOpDeptNo(user.getDeptId().toString());
        etyLog.setOpDeptName(user.getDeptName());
        etyLog.setOpUserNo(user.getUserNo());
        etyLog.setOpUserName(user.getUserName());
        etyLog.setOpAction("派单到下级部门");
        etyLog.setOpBtnId(-1);
        desc = sender.getSbdeptName();
        etyLog.setWsDesc("转办工单（" + desc + "）");
        etyLog.setWsOpen(1);
        etyLog.setOpDesc("提交到下级部门（" + desc + "）");
        etyLog.setEffectFlag(1);
        gxqTelWFLogService.save(etyLog);
    }

    /**
     * 2023/1/10
     * 修改GxqTwfSendBackEty工单信息
     * @param GxqTwfSendBackEty
     * @return 响应结果
     */
    @PostMapping("/editSendBackDept")
    public AjaxResult editSendBackDept(GxqTwfSendBackEty GxqTwfSendBackEty) {
        //保存响应结果
        boolean flag = false;
        SysUser user = ShiroUtils.getSysUser();
        GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
        if(GxqTwfSendBackEty != null) {
            //拟派多个部门
            GxqTwfSendBackEty updateSendBackEty = new GxqTwfSendBackEty();
            BeanUtils.copyBeanProp(updateSendBackEty, GxqTwfSendBackEty);
            if (StringUtils.isNotEmpty(GxqTwfSendBackEty.getSbdeptId())) {
                String[] arrDetpIdX = GxqTwfSendBackEty.getSbdeptId().split(",");
                String[] arrDetpNameX = GxqTwfSendBackEty.getSbdeptName().split(",");
                for (int i = 0; i < arrDetpIdX.length; i++) {
                    updateSendBackEty.setSbdeptId(arrDetpIdX[i]);
                    updateSendBackEty.setSbdeptName(arrDetpNameX[i]);
                    try {
                        // 默认第一条为修改
                        if ( i == 0) {
                            UpdateWrapper<GxqTwfSendBackEty> sbWrapper = new UpdateWrapper<>();
                            sbWrapper
                                    .set("SeqCode", updateSendBackEty.getSeqCode())
                                    .set("SeqName", updateSendBackEty.getSeqName())
                                    .set("SbdeptId", updateSendBackEty.getSbdeptId())
                                    .set("SbdeptName", updateSendBackEty.getSbdeptName())
                                    .set("SortCode", updateSendBackEty.getSortCode())
                                    .set("SortName", updateSendBackEty.getSortName())
                                    .set("DealCode", updateSendBackEty.getDealCode())
                                    .set("DealName", updateSendBackEty.getDealName())
                                    .set("SendDesc", updateSendBackEty.getSendDesc())
                                    .set("BackLimit", updateSendBackEty.getBackLimit())
                                    .set("SendRemark", updateSendBackEty.getSendRemark())
                                    .set("isDelay", updateSendBackEty.getIsDelay())
                                    .eq("PkId", updateSendBackEty.getPkId());
                            //执行修改方法
                            flag = gxqWfSendBackService.update(sbWrapper);
                            if (flag){
                                etyLog.setWfId(updateSendBackEty.getWfId());
                                etyLog.setOpDeptNo(user.getDeptId().toString());
                                etyLog.setOpDeptName(user.getDeptName());
                                etyLog.setOpUserNo(user.getUserNo());
                                etyLog.setOpUserName(user.getUserName());
                                String temp = "调整办理部门及要求(" + updateSendBackEty.getSbdeptName() + ")";
                                etyLog.setOpAction("修改");
                                etyLog.setOpBtnId(-1);
                                etyLog.setWsDesc(temp);
                                etyLog.setWsOpen(1);
                                etyLog.setOpDesc(temp);
                                etyLog.setEffectFlag(-1);
                                flag =  gxqTelWFLogService.save(etyLog);
                            }
                        } else {
                            // 新增派单
                            updateSendBackEty.setSendTime(new Date());
                            // 修改截至日期
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            updateSendBackEty.setBackLimit(sdf.parse(commonService.getNxetBackLimit(5)));
                            flag = gxqWfSendBackService.save(updateSendBackEty);
                            etyLog.setWfId(updateSendBackEty.getWfId()); //[tWorkFormBase]PkId
                            etyLog.setOpDeptNo(user.getDeptId().toString());
                            etyLog.setOpDeptName(user.getDeptName());
                            etyLog.setOpUserNo(user.getUserNo());
                            etyLog.setOpUserName(user.getUserName());
                            etyLog.setOpAction("提交初稿");
                            etyLog.setOpBtnId(-1);
                            String temp = "";
                            String desc = "";
                            temp = updateSendBackEty.getSbdeptName() != null ? updateSendBackEty.getSbdeptName() : "";
                            desc = "主办：";
                            desc += temp;
                            etyLog.setWsDesc("拟派工单（" + desc + "）"); //Show In website //2014-3-27 1->0
                            etyLog.setWsOpen(1); //website ShowFlag
                            etyLog.setOpDesc("提交内容概要：" + desc);
                            etyLog.setEffectFlag(1);
                            flag =  gxqTelWFLogService.save(etyLog);
                        }
                    } catch (Exception e) {
                        this.logger.debug("add main [tWfSendBack] fail: " + e.getMessage());
                        return AjaxResult.error();
                    }
                }
            }
        }
        return toAjax(flag);
    }

}
